package com.google.code.lightsomy.web;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * Delegates requests to default servlet using regexp.
 * 
 * @author Viktoras Agejevas
 *
 */
public class ResourcesFilter implements Filter {

	private FilterConfig config;
	
	private Pattern pattern;
	
	
	@Override
	public void destroy() {
		config = null;
		pattern = null;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) 
			throws IOException, ServletException {

		if (request instanceof HttpServletRequest) {
			HttpServletRequest req = (HttpServletRequest) request;
			
			if (pattern != null) {
				Matcher m = pattern.matcher(req.getRequestURI());
				
				if (m.matches()) {
					ServletContext ctx = config.getServletContext();
					ctx.getNamedDispatcher("default").forward(request, response);
					return;
				}
			}
		}
		
		filterChain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		config = filterConfig;
		String regex = config.getInitParameter("regex");
		
		if (regex != null) {
			pattern = Pattern.compile(regex);
		}
	}

}
